package fina2.dcs.security;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Remove;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.log4j.Logger;
import org.jboss.annotation.ejb.LocalBinding;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;


@Stateless
@Scope(ScopeType.SESSION)
@Name("userPermSession")
@LocalBinding(jndiBinding = "UserPermissionSession/local")
@AutoCreate
public class UserPermissionSession implements UserPermissionLocal, Serializable {
	@PersistenceContext
	private EntityManager em;

	@EJB
	private RoleLocal roleLocal;

	
	private Logger log=Logger.getLogger(getClass());

	public List<String> loadPermissionsByUserId(BigDecimal userId) {

		List<String> perms = new ArrayList<String>();
		try {
			perms = em.createQuery("SELECT p.idName FROM " + Permission.class.getName() + " p WHERE p.id IN(SELECT up.userPermPk.permissionId FROM " + UserPermission.class.getName() + " up WHERE up.userPermPk.userId=" + userId + ")").getResultList();
			List<String> permsByRole = roleLocal.loadPermissions(userId);
			if (permsByRole != null) {
				for (String s : permsByRole) {
					if (!perms.contains(s))
						perms.add(s);
				}
			}
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}

		return perms;
	}

	@Remove
	public void remove() {

	}
}
